package {

import flash.display.*;
import flash.net.*;
import flash.events.*;
import flash.filters.*;
import flash.utils.getTimer;
import flash.utils.describeType;

import r1.deval.D;
import org.libspark.asreflect.ASReflect;
import org.libspark.asreflect.Method;
import org.libspark.asreflect.Type;

import com.threerings.util.Util;

import aduros.util.F;

import com.whirled.*;

[SWF(width="100", height="100")]
public dynamic class Hackles extends Sprite
{
    public function Hackles ()
    {
        _ctrl = new PetControl(this);
        _ctrl.addEventListener(ControlEvent.CHAT_RECEIVED, onChat);

        var type :Type = ASReflect.getType(PetControl);
        for each (var method :Method in type.methods) {
            D.importFunction(method.name, _ctrl[method.name]);
        }

        D.importClass(EntityControl);
        D.importClass(PetControl);
        D.importClass(ControlEvent);

        D.importFunction("trace", _ctrl.sendChat);
        D.importFunction("getTimer", getTimer);
        D.importFunction("describeType", describeType);
        D.importFunction("navigateToURL", navigateToURL);
        D.importFunction("woof", F.callback(_ctrl.sendChat, "^_^"));
        D.importFunction("eval", eval);

        _context = {
            ctrl: _ctrl
        };

        _ctrl.registerCustomConfig(function () :Sprite {
            var s :Sprite = new Sprite();
            s.graphics.beginFill(0xff0000);
            s.graphics.drawRect(0, 0, 100, 100);
            s.graphics.endFill();
            return s;
        });

        addChild(new ICON());
    }

    protected function eval (code :String) :void
    {
        try {
            var result :Object = D.eval(code, _context, this);
            if (result != null) {
                _ctrl.sendChat("= " + String(result));
            }
        } catch (error :Error) {
            _ctrl.sendChat(error.toString());
            trace(error.getStackTrace());
        }

        var funcs :Object = D.parseFunctions(code);
        if (funcs != null) {
            Util.init(_context, funcs);
        }
    }

    protected function onChat (event :ControlEvent) :void
    {
        if (event.name != _ctrl.getMyEntityId() &&
            _ctrl.getOwnerId() == _ctrl.getInstanceId() &&
            _ctrl.getEntityProperty(EntityControl.PROP_MEMBER_ID, event.name) == _ctrl.getOwnerId()) {
            eval(event.value as String);
        }
    }

    protected var _ctrl :PetControl;
    protected var _context :Object = {};

    // Yanked from http://kermodog.deviantart.com/art/Dog-Sprite-Bark-89510958
    [Embed(source="dog.gif")]
    protected static const ICON :Class;
}
}
